//
//  UserShareDetailController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/28.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "UserShareDetailController.h"
#import "UserCommentCell.h"
#import "ShareDetailHeadView.h"
#import "Define.h"
#import "UserCommentModel.h"
#import <BmobSDK/Bmob.h>
#import "MJRefresh.h"

@interface UserShareDetailController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) ShareDetailHeadView *tableViewHeadView;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *commentArray;

@property (nonatomic, strong) UITextField *commentTextField;
@property (nonatomic, strong) UIButton *publishButton;

@property (nonatomic, strong) NSMutableString *commentString;
@property (nonatomic, strong) UIView *bottomView;

@end

static NSString *cellIndentifier = @"cell";

@implementation UserShareDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.commentArray = [NSMutableArray array];
    [self achiveShareCommentFromService];
    [self createView];
    
    // 添加键盘弹出的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    // 添加键盘回收的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardHidden:) name:UIKeyboardWillHideNotification object:nil];
    // 添加键盘Frame改变的通知 (切换键盘时, 也会触发键盘弹出的方法, 所以很少用);
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
    
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefreshAction)];
//    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefreshAction)];
}

- (void)createView
{
    CGSize tableViewHeadView = [self stringSizeWithFont:[UIFont systemFontOfSize:15 weight:1] string:self.model.shareContent width:kScreenWidth];
    
    _tableViewHeadView = [[ShareDetailHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, tableViewHeadView.height + 200)];
    _tableViewHeadView.model = self.model;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 50) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UserCommentCell class] forCellReuseIdentifier:cellIndentifier];
    self.tableView.separatorStyle = NO;
    self.tableView.rowHeight = 200;
    self.tableView.tableHeaderView = self.tableViewHeadView;
    [self.view addSubview:_tableView];
    
//    底部的View
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight - 64 - 50, kScreenWidth, 50)];
    // 评论textField
    self.commentTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, kScreenWidth - 80, 30)];
    self.commentTextField.delegate = self;
    self.commentTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.commentTextField.placeholder = @"发表一个评论吧";
    [_bottomView addSubview:_commentTextField];
    
    // 发表评论按钮
    self.publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.publishButton.frame = CGRectMake(kScreenWidth - 60, self.commentTextField.y, 50, self.commentTextField.height);
    self.publishButton.layer.cornerRadius = self.publishButton.height / 4;
    self.publishButton.layer.borderWidth = 1;
    [self.publishButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.publishButton addTarget:self action:@selector(publishButtonAction:)forControlEvents:UIControlEventTouchUpInside];
    [self.publishButton setTitle:@"发表" forState:UIControlStateNormal];
    
    self.publishButton.layer.borderColor = [UIColor grayColor].CGColor;
    _bottomView.backgroundColor = [UIColor whiteColor];
    [_bottomView addSubview:_publishButton];
    
    [self.view addSubview:_bottomView];
}

// 返回tableViewHeadView的高度;
- (CGSize)stringSizeWithFont:(UIFont *)font string:(NSString *)string width:(CGFloat)width
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size;
}


#pragma mark --------------------  评论tableView相关设置 ------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.commentArray.count == 0) {
        return 0;
    }
    return self.commentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    cell.userCommentModel = self.commentArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserCommentModel *model = self.commentArray[indexPath.row];
    CGSize size = [self stringSizeWithFont:[UIFont systemFontOfSize:15 weight:1] string:model.commentContent width:kScreenWidth];
    return size.height + 50;
}

#pragma mark ----------------- 从服务器获取评论Array -----------------
- (void)achiveShareCommentFromService
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"UserPublic"];
    [bquery getObjectInBackgroundWithId:self.model.objectId block:^(BmobObject *object, NSError *error) {
        if (error)
        {
            NSLog(@"%@",error);
        }
        else
        {
            
            NSString *serviceString = [object objectForKey:@"shareComment"];
            if (serviceString.length != 0)
            {
                self.commentString = [NSMutableString stringWithString:serviceString];
                
                NSArray *array = [serviceString componentsSeparatedByString:@"(userComment)"];
                for (int i = 0; i < array.count - 1; i++)
                {
                    NSString *oneCommentString = array[i + 1];
                    NSLog(@"%@",oneCommentString);
                    
                    UserCommentModel *model = [[UserCommentModel alloc]init];
                    
                    // model.userInfoModel.username 的赋值;
                    NSString *oneusernameString = [[oneCommentString componentsSeparatedByString:@"(username)"]lastObject];
                    model.userInfoModel.username = [oneusernameString componentsSeparatedByString:@"(userheadImage)"].firstObject;
                    
                    // model.userInfoModel.userHeadImage 的赋值
                    NSString *userImageLastobject = [oneCommentString componentsSeparatedByString:@"(userheadImage)"].lastObject;
                    model.userInfoModel.userHeadImage = [userImageLastobject componentsSeparatedByString:@"(shareComment)"].firstObject;
                    NSLog(@"=========== %@",model.userInfoModel.userHeadImage);
                    
                    // model.commentContent 的赋值
                    NSString *userCommentLast = [oneCommentString componentsSeparatedByString:@"(shareComment)"].lastObject;
                    model.commentContent = [userCommentLast componentsSeparatedByString:@"(userCommentTime)"].firstObject;
                    NSLog(@"%@",model.commentContent);
                    
                    // model.commentTime 的赋值
                    NSString *usercommentTime = [oneCommentString componentsSeparatedByString:@"(userCommentTime)"].lastObject ;
                    model.commentTime = usercommentTime;
                    [self.commentArray addObject:model];
                }
            }
            else
            {
                self.commentString = [NSMutableString string];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.commentTextField resignFirstResponder];
}

#pragma mark ---------------- 点击发表按钮执行的方法 -------------
- (void)publishButtonAction:(UIButton *)button
{
    if (self.commentTextField.text.length == 0)
    {
        return;
    }
    UserCommentModel *commentModel = [[UserCommentModel alloc]init];
    // 获取当前用户 制作commentModel;
    BmobUser *bUser = [BmobUser getCurrentUser];
    commentModel.userInfoModel.username = [bUser objectForKey:@"username"];
    BmobFile *bUserHeadImage = [bUser objectForKey:@"userheadImage"];
    commentModel.userInfoModel.userHeadImage = bUserHeadImage.url;
    commentModel.commentContent = self.commentTextField.text;
    NSString *username = [NSString stringWithFormat:@"(username)%@",commentModel.userInfoModel.username];
    NSString *userheadImage = [NSString stringWithFormat:@"(userheadImage)%@",commentModel.userInfoModel.userHeadImage];
    NSString *userComment = [NSString stringWithFormat:@"(shareComment)%@",self.commentTextField.text];
    
    // 添加当前时间数据
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MM.dd HH:mm"];
    NSString *timeString = [formatter stringFromDate:date];
    NSString *time = [NSString stringWithFormat:@"(userCommentTime)%@",timeString];
    
    // 整和成字符串添加到数据库中;
    NSString *comment = [NSString stringWithFormat:@"(userComment)%@%@%@%@",username, userheadImage, userComment, time];

    [self.commentString appendString:comment];
    
    BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:@"UserPublic" objectId:self.model.objectId];
    
    [bmobObject setObject:self.commentString forKey:@"shareComment"];
    [bmobObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful)
        {
            NSLog(@"跟新成功");
        }
        else
        {
            NSLog(@"%@",error);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
    
    // 点击button之后, 让键盘回收
    [self.commentTextField resignFirstResponder];
    self.commentTextField.text = nil;
    
    // 点击之后刷新界面;
    [self.commentArray removeAllObjects];
    [self achiveShareCommentFromService];
    
}

#pragma mark ----------------- 键盘frame改变通知 -----------------------------
- (void)keyBoardShow:(NSNotification *)notification
{
    // 键盘弹出的时候相当于系统自己发出了一个 post 无需我们自己去调用;
    // 1. 得到键盘所有信息
    NSDictionary *info = [notification userInfo];
//    NSLog(@"%@", info);
    // 2. 得到键盘弹出之后的 frame
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 3. 得到键盘的高度;
    CGSize size = [value CGRectValue].size;
//    NSLog(@"%f", size.height);
    self.bottomView.y = kScreenHeight - 64 - size.height - 50;
    
//    self.publishButton.frame = CGRectMake(kScreenWidth - 50, kScreenHeight - 49 - 64 - 30 - size.height, 50, 30);
//    self.commentTextField.frame = CGRectMake(0, kScreenHeight - 49 - 64 - 30 - size.height, kScreenWidth - 50 , 30);
}

// 键盘frame改变执行的通知
- (void)keyBoardChange:(NSNotification *)notification
{
    // 1. 得到键盘所有信息
    NSDictionary *info = [notification userInfo];

    // 2. 得到键盘弹出之后的 frame
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    // 3. 得到键盘的高度;
    CGSize size = [value CGRectValue].size;
//    NSLog(@"键盘改变%f", size.height);
}

- (void)keyBoardHidden:(NSNotification *)nitification
{
    self.bottomView.frame = CGRectMake(0, kScreenHeight - 64 - 50, kScreenWidth, 50);

}

#pragma mark ------------------------  加载 / 刷新方法 -----------------------------
- (void)headerRefreshAction
{
    [self.commentArray removeAllObjects];
    [self achiveShareCommentFromService];
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
}
- (void)footerRefreshAction
{
    [self.tableView.footer endRefreshing];
}




@end
